package com.horoscope.astrology.zodiac.signs.free.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.adapter.ArticleDetailAdapter
import com.horoscope.astrology.zodiac.signs.free.bean.ArticleBean
import com.horoscope.astrology.zodiac.signs.free.bean.ArticleResultDataBean
import com.horoscope.astrology.zodiac.signs.free.bean.BaseBean
import com.horoscope.astrology.zodiac.signs.free.bean.PushNewBean
import com.horoscope.astrology.zodiac.signs.free.network.NetworkEngine
import com.horoscope.astrology.zodiac.signs.free.network.NetworkListener
import com.horoscope.astrology.zodiac.signs.free.utils.ArticleDetailDecoration
import com.horoscope.astrology.zodiac.signs.free.utils.EventType
import com.horoscope.astrology.zodiac.signs.free.utils.FlurryEventUtil
import com.horoscope.astrology.zodiac.signs.free.utils.ToastUtil
import kotlinx.android.synthetic.main.back_title.*

/**
 * 文章详情页
 * 有两种进入方式：
 * 1、从文章列表点击进入 需要传title 文章详情 推送判断
 * 2、收到推送进入 需要传 文章的url 然后获取title 和 paragraphs
 */
class ArticleDetailActivity : BaseActivity() {

    var title: String = ""
    lateinit var list: ArrayList<ArticleBean>

    private lateinit var mAdapter: ArticleDetailAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_article_detail)
        initTitleBar(
            this,
            R.id.btn_back_edit_name,
            R.id.text_view_back_title,
            ""
        )
        showLoading()
        initView()
        articleContent()
    }

    private fun initView() {
        list = ArrayList()
        list.clear()
        mRecyclerView = findViewById(R.id.recycler_view_article_detail)
        mAdapter = ArticleDetailAdapter(this)
        mRecyclerView.adapter = mAdapter
        mRecyclerView.layoutManager = LinearLayoutManager(this)
        mRecyclerView.addItemDecoration(ArticleDetailDecoration(0f, 20f))
        btn_back_edit_name.setOnClickListener {
            if (intent.getBooleanExtra(PUSH, false)) {
                val intent = Intent(this, MainActivity::class.java)
                intent.putExtra("page", 2)
                startActivity(intent)
            }
            finish()

        }
    }

    private fun articleContent() {
        val url: String? = intent.getStringExtra("article_url")
        if (url == null) {
            if (intent.getSerializableExtra(TYPE) != null) {
                list = intent.getParcelableArrayListExtra(TYPE)
                title = intent.getStringExtra("title")
                val size = list.size - 1
                for (i in 0..size) {
                    if (i == 2 || (i - 7) % 5 == 0) {
                        list.add(i, ArticleBean(true))
                    }
                }
                initData()
            }
        } else {
            FlurryEventUtil.putDataToEvent(EventType.TYPE_APP_OPEND, "type", SplashActivity.PUSH_PM)
            activityShowAd("Interstitial_Splash")
            val urlList = url.split("/")
            NetworkEngine.getArticleForPushUrl("article", urlList[urlList.size - 2] + "/",
                object : NetworkListener<PushNewBean>() {
                    override fun onSuccess(t: PushNewBean) {
                        if (t.data.size > 0) {
                            buildData(t.data[0])
                        } else {
                            showLoaded()
                        }
                    }

                    override fun onFailed(t: PushNewBean) {
                        super.onFailed(t)
                        if (t.data.size > 0) {
                            buildData(t.data[0])
                        } else {
                            showLoaded()
                        }
                    }

                    override fun onError(e: String?) {
                        super.onError(e)
                        showLoaded()
                        ToastUtil.showRewardError(this@ArticleDetailActivity)
                    }
                })

        }
    }

    private fun buildData(data: ArticleResultDataBean) {
        if (list.size > 0) list.clear()
        // 先添加三张图片
        for (u in data.images) {
            val b = ArticleBean()
            b.url = u
            b.type = "image"
            list.add(b)
        }
        // 添加正文
        list.addAll(data.paragraphs)
        // 添加广告
        val size = list.size - 1
        for (i in 0..size) {
            if (i == 2 || (i - 7) % 5 == 0) {
                list.add(i, ArticleBean(true))
            }
        }
        title = data.title
        //
        initData()
    }

    private fun initData() {
        mAdapter.setData(list)
        mAdapter.setTitle(title)
        // 上报文章title
        pushArticleTitle(title)
        showLoaded()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        if (intent.getBooleanExtra(PUSH, false)) {
            val intent = Intent(this, MainActivity::class.java)
            intent.putExtra("page", 2)
            startActivity(intent)
        }
        finish()
    }


    companion object {
        private val TAG = ArticleDetailActivity::class.java.simpleName
        private const val TYPE = "article"
        private const val TITLE = "title"
        private const val PUSH = "push"

        fun generateIntent(
            activity: Context,
            title: String,
            list: ArrayList<ArticleBean>,
            fromPush: Boolean? = false
        ): Intent {
            val intent = Intent(activity, ArticleDetailActivity::class.java)
            intent.putExtra(TITLE, title)
            intent.putExtra(TYPE, list)
            intent.putExtra(PUSH, fromPush)
            return intent
        }
    }

    private fun pushArticleTitle(title: String) {
        NetworkEngine.postArticleTitle(title, object : NetworkListener<BaseBean>() {
            override fun onSuccess(t: BaseBean) {
                //To change body of created functions use File | Settings | File Templates.
                Log.d(TAG, "onSuccess but title=：$title")
            }

            override fun onFailed(t: BaseBean) {
                super.onFailed(t)
                Log.e(TAG, "" + t.message)
            }

            override fun onError(e: String?) {
                super.onError(e)
                Log.e(TAG, e)
            }
        })
    }
}